package com.begamer.card.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.MailThread;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.Constant;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.Statics;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.DailyTaskData;
import com.begamer.card.common.util.binRead.LevelGiftData;
import com.begamer.card.common.util.binRead.TakeCardTimeData;
import com.begamer.card.common.util.binRead.VipData;
import com.begamer.card.common.util.binRead.VitalityData;
import com.begamer.card.json.command2.ActiveJson;
import com.begamer.card.json.command2.ActiveResultJson;
import com.begamer.card.json.command2.ActivityGJson;
import com.begamer.card.json.command2.ActivityGResultJson;
import com.begamer.card.json.command2.ActivityInfoJson;
import com.begamer.card.json.command2.ActivityInfoResultJson;
import com.begamer.card.json.command2.ActivityJson;
import com.begamer.card.json.command2.ActivityResultJson;
import com.begamer.card.json.command2.ActivityRewardJson;
import com.begamer.card.json.command2.ActivityRewardResultJson;
import com.begamer.card.json.command2.ExchangeJson;
import com.begamer.card.json.command2.ExchangeResultJson;
import com.begamer.card.json.command2.GiftCodeJson;
import com.begamer.card.json.command2.GiftCodeResultJson;
import com.begamer.card.json.command2.GiftJson;
import com.begamer.card.json.command2.TaskJson;
import com.begamer.card.json.command2.TaskResultJson;
import com.begamer.card.json.element.ActivityDElement;
import com.begamer.card.json.element.ActivityElement;
import com.begamer.card.json.element.ActivityGElement;
import com.begamer.card.json.element.ActivityInfoExchangeElement;
import com.begamer.card.json.element.ShopElement;
import com.begamer.card.json.element.TaskElement;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.pojo.Activity;
import com.begamer.card.model.pojo.ActivityInfo;
import com.begamer.card.model.pojo.LogBuy;
import com.begamer.card.model.pojo.LotRank;

public class ActivityController extends AbstractMultiActionController {
	private static Logger logger = Logger.getLogger(AchieveController.class);
	private static Logger playlogger = PlayerLogger.logger;
	private static Logger errorlogger = ErrorLogger.logger;
	
	public ModelAndView activityList(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ActivityJson aj = JSONObject.toJavaObject(jsonObject, ActivityJson.class);
			ActivityResultJson arj = new ActivityResultJson();
			if (aj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(aj.playerId, request.getSession());
				if (pi != null)
				{
					// 校验阶段
					int errorcode = 0;
					if (errorcode == 0)
					{
						if (!UiController.checkMode(19, pi))
						{
							errorcode = 56;
						}
					}
					// 功能阶段
					if (errorcode == 0)
					{
						List<ActivityElement> aes = new ArrayList<ActivityElement>();
						List<Activity> activitys = Cache.getInstance().getActivitys();
						if (activitys != null)
						{
							for (int i = 0; i < activitys.size(); i++)
							{
								Activity a = activitys.get(i);
								if (a != null && a.getSell() == 0)
								{
									if (a.activityId == 6 || a.getActivityId() == 8 || a.getActivityId() == 9)// 聚宝盆||大风车
									{
										if (a.getSttime() != null && a.getEndtime() != null && a.getSttime().length() > 0 && a.getEndtime().length() > 0)
										{
											int time = (int) (StringUtil.getTimeStamp(a.getEndtime() + " 24:00:00") - System.currentTimeMillis()) / 1000;
											if (time <= 0)
											{
												continue;
											}
											if (StringUtil.getTimeStamp(a.getSttime() + " 00:00:00") - System.currentTimeMillis() > 0)
											{
												continue;
											}
										}
									}
									ActivityElement ae = new ActivityElement();
									ae.id = a.getActivityId();
									ae.name = a.getActivityName();
									ae.type = a.getType();
									ae.weight = a.getWeight();
									if (a.type == 4)
									{
										List<ActivityInfo> acti = Cache.instance.getActivityInfosForId(a.getActivityId());
										if (acti != null && acti.size() > 0)
										{
											for (ActivityInfo ai : acti)
											{
												String exnum = pi.player.getExchange();// 27-1,
												boolean is = true;
												if (exnum != null && exnum.trim().length() > 0)
												{
													String[] exchange = exnum.split(",");// 27-1
													for (int n = 0; n < exchange.length; n++)
													{
														String[] ex = exchange[n].split("-");// 27
														int id = Integer.parseInt(ex[0]);
														int num = Integer.parseInt(ex[1]);
														if (id == ai.getId() && ai.getSole() > 0 && num >= ai.getSole())// 30
														{
															ae.t = 0;
															is = false;
															break;
														}
													}
												}
												if (is)
												{
													boolean n1 = true;
													boolean n2 = true;
													boolean n3 = true;
													if (ai.getNeedType() > 0)
													{
														n1 = Statics.check(pi, ai.getNeedType(), ai.getNeedId(), ai.getNeedNum());
													}
													if (ai.getNeedType2() > 0)
													{
														n2 = Statics.check(pi, ai.getNeedType2(), ai.getNeedId2(), ai.getNeedNum2());
													}
													if (ai.getNeedType3() > 0)
													{
														n3 = Statics.check(pi, ai.getNeedType3(), ai.getNeedId3(), ai.getNeedNum3());
													}
													if (n1 && n2 && n3)
													{
														ae.t = 1;
														is = false;
													}
													else
													{
														ae.t = 0;
													}
												}
												if (ae.t == 1)
												{
													break;
												}
											}
										}
									}
									else if (a.type == 2)// 登陆
									{
										boolean is = true;
										String loginDayAward = pi.player.getLoginDayAward();
										int day = 0;
										if (pi.player.getLoginDayNum() <= 7)
										{
											day = pi.player.getLoginDayNum();
										}
										else
										{
											day = 7;
										}
										if (loginDayAward != null && loginDayAward.length() > 0)
										{
											HashMap<Integer, String> map = new HashMap<Integer, String>();
											String[] temp = loginDayAward.split("&");
											for (int j = 0; j < temp.length; j++)
											{
												if (temp[j] != null && temp[j].length() > 0)
												{
													map.put(StringUtil.getInt(temp[j]), temp[j]);
												}
											}
											for (int j = 1; j <= day; j++)
											{
												ShopElement se = new ShopElement();
												se.setId(j);
												if (!map.containsKey(j))
												{
													ae.t = 1;
													is = false;
													break;
												}
											}
											if (is)
											{
												ae.t = 0;
											}
										}
										else
										{
											for (int j = 0; j <= day; j++)
											{
												ae.t = 1;
												is = false;
												break;
											}
											if (is)
											{
												ae.t = 0;
											}
										}
									}
									else if (a.type == 3)// 等级
									{
										boolean is = true;
										String levelgift = pi.player.getLevelgift();
										if (levelgift != null && levelgift.length() > 0)
										{
											for (int j = 1; j <= pi.player.getLevel(); j++)
											{
												LevelGiftData lgData = LevelGiftData.getLevelGiftData(j);
												if (lgData != null)
												{
													if (levelgift != null && levelgift.length() > 0)
													{
														if (!levelgift.contains(lgData.id + ""))
														{
															ae.t = 1;
															is = false;
															break;
														}
													}
													else
													{
														ae.t = 1;
														is = false;
														break;
													}
												}
											}
											if (is)
											{
												ae.t = 0;
											}
										}
										else
										{
											for (int j = 1; j <= pi.player.getLevel(); j++)
											{
												LevelGiftData lgData = LevelGiftData.getLevelGiftData(j);
												if (lgData != null)
												{
													ae.t = 1;
													is = false;
													break;
												}
											}
											if (is)
											{
												ae.t = 0;
											}
										}
									}
									else if (a.type == 8)// 大风车
									{
										String turnTimes = pi.player.getLottoTimes();
										boolean turnIn = false;
										if (turnTimes != null && turnTimes.length() > 0)// 存储次数字段不为空
										{
											String[] turn = turnTimes.split("&");
											for (int e = 0; e < turn.length; e++)
											{
												String[] temp = turn[e].split("-");
												if (StringUtil.getInt(temp[1]) > 0)// 次数大于0，可抽奖，t=1
												{
													ae.t = 1;
													turnIn = true;
													break;
												}
											}
											if (!turnIn)// 存储次数字段不为空，但是次数小于0
											{
												ae.t = 0;
											}
										}
										else
										// 字段为空
										{
											ae.t = 0;
										}
									}
									else if (a.type == 9)// 限时神将
									{
										TakeCardTimeData tctd = TakeCardTimeData.getData(1);
										LotRank lr = Cache.getInstance().getLotRankById(pi.player.getId());
										boolean is = true;
										if (lr != null)
										{
											if ((System.currentTimeMillis()-(lr.getLastLotTime() + tctd.time * 3600 * 1000)) >= 0)
											{
												ae.t = 1;
												is = false;
											}
										}
										else
										{
											ae.t = 1;
											is = false;
										}
										if (is)
										{
											ae.t = 0;
										}
									}
									else
									{
										ae.t = 0;
									}
									aes.add(ae);
								}
							}
						}
						else
						{
							errorlogger.info("activity is null");
						}
						// 排序
						for (int m = 0; m < aes.size(); m++)
						{
							for (int k = aes.size() - 1; k > 0; k--)
							{
								if (aes.get(k).getWeight() > aes.get(k - 1).getWeight())// 交换位置
								{
									ActivityElement ae = new ActivityElement();
									ae = aes.get(k);
									aes.set(k, aes.get(k - 1));
									aes.set(k - 1, ae);
								}
							}
						}
						arj.acts = aes;
					}
					else
					{
						arj.errorCode = errorcode;
					}
					playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pi.player.getId() + "|" + pi.player.getName() + "|等级：" + pi.player.getLevel() + "|请求活动界面");
				}
				else
				{
					arj.errorCode = -3;
				}
			}
			else
			{
				arj.errorCode = -1;
			}
			
			// 获取参数
			Cache.recordRequestNum(arj);
			String msg = JSON.toJSONString(arj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 每日任务列表 **/
	public ModelAndView taskList(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			TaskJson tj = JSONObject.toJavaObject(jsonObject, TaskJson.class);
			TaskResultJson trj = new TaskResultJson();
			if (tj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(tj.playerId, request.getSession());
				if (pi != null)
				{
					// 校验阶段
					int errorcode = 0;
					if (errorcode == 0)
					{
						if (!UiController.checkMode(19, pi))
						{
							errorcode = 56;
						}
					}
					// 功能阶段
					if (errorcode == 0)
					{
						List<DailyTaskData> dts = new ArrayList<DailyTaskData>();
						dts = DailyTaskData.getDailyTaskDatas();
						List<TaskElement> tes = new ArrayList<TaskElement>();
						
						String taskComplete = pi.player.getDailyTaskComplete();
						String[] ss = null;
						HashMap<Integer, Integer> completeMap = new HashMap<Integer, Integer>();
						if (taskComplete != null)
						{
							ss = taskComplete.split(",");
							for (int j = 0; j < ss.length; j++)
							{
								if (ss[j] != null && ss[j].length() > 0)
								{
									String[] temp = ss[j].split("-");
									if (temp[0] != null && temp[0].length() > 0 && temp[1] != null && temp[1].length() > 0)
									{
										if (!completeMap.containsKey(StringUtil.getInt(temp[0])))
										{
											completeMap.put(StringUtil.getInt(temp[0]), StringUtil.getInt(temp[1]));
										}
									}
									
								}
							}
						}
						
						for (int i = 0; i < dts.size(); i++)
						{
							String taskState = pi.player.getDailyTaskState();
							boolean a = true;
							boolean b = true;
							if (dts.get(i) != null)
							{
								String type = "";
								TaskElement te = new TaskElement();
								te.setId(dts.get(i).id);
								te.setIcon(dts.get(i).icon);
								te.setName(dts.get(i).name);
								te.setDescription(dts.get(i).description);
								te.setUnlockLevel(dts.get(i).unlockcondition);
								te.setUlDesc(dts.get(i).unlockdescription);
								te.setActiveNum(dts.get(i).num);
								// 月卡特殊处理
								if (pi.player.getVipMonthType() == 1 && pi.player.getVipMonthDay() > 0 && i == 10)
								{
									type = taskState.substring(i, i + 1);
									if (StringUtil.getInt(type) == 0)
									{
										pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
										taskState = pi.player.getDailyTaskState();
									}
								}
								// vip扫荡券奖励特殊处理
								if (i == 7)
								{
									if (pi.player.getVipLevel() > 0)
									{
										type = taskState.substring(i, i + 1);
										if (StringUtil.getInt(type) == 0)
										{
											pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
											taskState = pi.player.getDailyTaskState();
										}
										List<String> s = new ArrayList<String>();
										VipData vData = VipData.getVipData(pi.player.getVipLevel());
										if (vData != null)
										{
											s.add(1 + "-" + "80001" + "," + vData.mission);
											te.setReward(s);
										}
									}
									else
									{
										continue;
									}
								}
								else
								{
									te.setReward(dts.get(i).reward);
								}
								if (completeMap != null && completeMap.size() > 0)
								{
									if (completeMap.containsKey(dts.get(i).id))
									{
										te.setNum(completeMap.get(dts.get(i).id));
									}
									else
									{
										te.setNum(0);
									}
								}
								else
								{
									te.setNum(0);
								}
								te.setSNum(dts.get(i).request);
								
								// 领取体力特殊处理
								// 00:00-13:00发给客户端第一个领取体力值任务 13:00-19：00
								String date1 = "13:00:00";
								String date2 = "00:00:00";
								String date3 = "19:00:00";
								String date4 = "12:00:00";
								String date5 = "18:00:00";
								String today = StringUtil.getDate(System.currentTimeMillis());
								long t1 = StringUtil.getTimeStamp(today + " " + date2);// 00
								long t2 = StringUtil.getTimeStamp(today + " " + date1);// 13
								long t3 = StringUtil.getTimeStamp(today + " " + date3);// 19
								long t4 = StringUtil.getTimeStamp(today + " " + date4);// 12
								long t5 = StringUtil.getTimeStamp(today + " " + date5);// 18
								long time = System.currentTimeMillis();
								if (time - t1 >= 0 && time - t2 <= 0)// 00-13
								{
									if (i == 11)
									{
										if (time - t4 >= 0)// 12-13
										{
											// 更改状态
											type = taskState.substring(i, i + 1);
											if (StringUtil.getInt(type) == 0)
											{
												
												pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
												taskState = pi.player.getDailyTaskState();
												
											}
										}
										type = pi.player.getDailyTaskState().substring(i, i + 1);
										te.setType(StringUtil.getInt(type));
										tes.add(te);
										b = false;
									}
								}
								if (time - t2 > 0 && time - t3 <= 0)// 13-19
								{
									if (i == 12)
									{
										if (time - t5 >= 0)// 18-19
										{
											type = taskState.substring(i, i + 1);
											if (StringUtil.getInt(type) == 0)
											{
												pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
												taskState = pi.player.getDailyTaskState();
											}
										}
										type = taskState.substring(i, i + 1);
										te.setType(StringUtil.getInt(type));
										tes.add(te);
										a = false;
									}
								}
								if ((!a && i == 11) || (!b && i == 12))
								{
									type = taskState.substring(i, i + 1);
									if (type != null && StringUtil.getInt(type) < 2)
									{
										te.setType(StringUtil.getInt(type));
										tes.add(te);
									}
								}
								if (a && b)
								{
									if (i != 11 && i != 12)
									{
										type = taskState.substring(i, i + 1);
										if (type != null && StringUtil.getInt(type) < 2)
										{
											te.setType(StringUtil.getInt(type));
											tes.add(te);
										}
									}
								}
							}
						}
						// 排序
						for (int m = 0; m < tes.size(); m++)
						{
							for (int k = tes.size() - 1; k > 0; k--)
							{
								if (tes.get(k).getType() > tes.get(k - 1).getType())// 交换位置
								{
									TaskElement te = new TaskElement();
									te = tes.get(k);
									tes.set(k, tes.get(k - 1));
									tes.set(k - 1, te);
								}
							}
						}
						trj.tes = tes;
						trj.active = pi.player.getActive();
						trj.activeState = pi.player.getActiveState();
					}
					else
					{
						trj.errorCode = errorcode;
					}
					playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pi.player.getId() + "|" + pi.player.getName() + "|等级：" + pi.player.getLevel() + "|请求任务界面");
				}
				else
				{
					trj.errorCode = -3;
				}
			}
			else
			{
				trj.errorCode = -1;
			}
			
			// 获取参数
			Cache.recordRequestNum(trj);
			String msg = JSON.toJSONString(trj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 修改任务完成进度及活动状态 **/
	public static void updateTaskComplete(int taskId, PlayerInfo pi, int num)
	{
		DailyTaskData dailyTaskData = DailyTaskData.getDailyTaskData(taskId);
		String complete = pi.player.getDailyTaskComplete();
		int newNum = 0;
		if (complete == null || complete.length() == 0)
		{
			pi.player.setDailyTaskComplete(taskId + "-" + num);
			if (num >= dailyTaskData.request)
			{
				String state = pi.player.getDailyTaskState();
				if (StringUtil.getInt(state.substring(taskId - 1, taskId)) == 0)
				{
					if (taskId == 14)
					{
						pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 2 + ""));// 修改任务状态
					}
					else
					{
						pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 1 + ""));// 修改任务状态
					}
				}
			}
		}
		else
		{
			String[] ss = complete.split(",");
			HashMap<Integer, Integer> completeMap = new HashMap<Integer, Integer>();
			for (int i = 0; i < ss.length; i++)
			{
				if (ss[i] != null && ss[i].length() > 0)
				{
					String[] temp = ss[i].split("-");
					if (!completeMap.containsKey(StringUtil.getInt(temp[0])))
					{
						completeMap.put(StringUtil.getInt(temp[0]), StringUtil.getInt(temp[1]));
					}
				}
			}
			if (completeMap != null && completeMap.size() > 0)
			{
				if (completeMap.containsKey(taskId))
				{
					newNum = completeMap.get(taskId) + num;
					if (newNum >= dailyTaskData.request)
					{
						String state = pi.player.getDailyTaskState();
						if (StringUtil.getInt(state.substring(taskId - 1, taskId)) == 0)
						{
							if (taskId == 14)
							{
								pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 2 + ""));// 修改任务状态
							}
							else
							{
								pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 1 + ""));// 修改任务状态
							}
						}
					}
					String str = "";
					for (int j = 0; j < ss.length; j++)
					{
						if (ss[j] != null && ss[j].length() > 0)
						{
							String[] temp = ss[j].split("-");
							if (StringUtil.getInt(temp[0]) == taskId)
							{
								ss[j] = temp[0] + "-" + newNum;
							}
							if (str != null && str.length() > 0)
							{
								str = str + "," + ss[j];
							}
							else
							{
								str = ss[j];
							}
						}
					}
					pi.player.setDailyTaskComplete(str);// 修改任务完成进度
				}
				else
				{
					pi.player.setDailyTaskComplete(pi.player.getDailyTaskComplete() + "," + taskId + "-" + num);
					if (num >= dailyTaskData.request)
					{
						String state = pi.player.getDailyTaskState();
						if (StringUtil.getInt(state.substring(taskId - 1, taskId)) == 0)
						{
							if (taskId == 14)
							{
								pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 2 + ""));// 修改任务状态
							}
							else
							{
								pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 1 + ""));// 修改任务状态
							}
						}
					}
				}
			}
		}
	}
	
	/** 领取每日任务奖励 **/
	public ModelAndView activityReward(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ActivityRewardJson arj = JSONObject.toJavaObject(jsonObject, ActivityRewardJson.class);
			ActivityRewardResultJson arrj = new ActivityRewardResultJson();
			if (arj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(arj.playerId, request.getSession());
				if (pi != null)
				{
					int errorcode = 0;
					// 校验阶段
					// 校验该任务是否完成或者奖励是否领取
					int taskId = arj.taskId;
					DailyTaskData dtd = DailyTaskData.getDailyTaskData(taskId);
					String state = pi.player.getDailyTaskState();
					if (dtd != null)
					{
						if (state != null && state.length() > 0)
						{
							if (StringUtil.getInt(state.substring(taskId - 1, taskId)) == 0)
							{
								errorcode = 90;
							}
							else if (StringUtil.getInt(state.substring(taskId - 1, taskId)) == 2)
							{
								errorcode = 91;
							}
						}
						else
						{
							errorcode = 90;
						}
					}
					else
					{
						errorlogger.info("taskdata is null");
					}
					// 功能阶段
					if (errorcode == 0)
					{
						// 改变任务状态
						pi.player.setDailyTaskState(StringUtil.replaceStr(state, taskId - 1, 2 + ""));//
						// 发放奖励
						List<String> reward = new ArrayList<String>();
						if (taskId == 8)
						{
							VipData vData = VipData.getVipData(pi.player.getVipLevel());
							if (vData != null)
							{
								reward.add("1" + "-" + "80001" + "," + vData.mission);
							}
						}
						else
						{
							reward = dtd.reward;
						}
						List<Integer> cardIds = new ArrayList<Integer>();
						if (reward != null && reward.size() > 0)
						{
							for (int i = 0; i < reward.size(); i++)
							{
								if (reward.get(i) != null && reward.get(i).length() > 0)
								{
									String[] ss = reward.get(i).split("-");
									String[] temp = ss[1].split(",");
									if (StringUtil.getInt(ss[0]) == 3)
									{
										cardIds.add(StringUtil.getInt(temp[0]));
									}
									Statics.getReward(StringUtil.getInt(ss[0]), ss[1], pi);
								}
							}
							if (cardIds.size() > 0)
							{
								pi.getNewUnitSkill(cardIds);
							}
						}
						if (taskId == 11)
						{
							pi.player.setVipMonthDay(pi.player.getVipMonthDay() - 1);
						}
						
						// 任务列表
						List<DailyTaskData> dts = new ArrayList<DailyTaskData>();
						dts = DailyTaskData.getDailyTaskDatas();
						List<TaskElement> tes = new ArrayList<TaskElement>();
						String taskState = pi.player.getDailyTaskState();
						String taskComplete = pi.player.getDailyTaskComplete();
						String[] ss = null;
						HashMap<Integer, Integer> completeMap = new HashMap<Integer, Integer>();
						if (taskComplete != null)
						{
							ss = taskComplete.split(",");
							for (int j = 0; j < ss.length; j++)
							{
								if (ss[j] != null && ss[j].length() > 0)
								{
									String[] temp = ss[j].split("-");
									if (temp[0] != null && temp[0].length() > 0 && temp[1] != null && temp[1].length() > 0)
									{
										if (!completeMap.containsKey(StringUtil.getInt(temp[0])))
										{
											completeMap.put(StringUtil.getInt(temp[0]), StringUtil.getInt(temp[1]));
										}
									}
									
								}
							}
						}
						
						for (int i = 0; i < dts.size(); i++)
						{
							boolean a = true;
							boolean b = true;
							if (dts.get(i) != null)
							{
								String type = "";
								TaskElement te = new TaskElement();
								te.setId(dts.get(i).id);
								te.setIcon(dts.get(i).icon);
								te.setName(dts.get(i).name);
								te.setDescription(dts.get(i).description);
								te.setUnlockLevel(dts.get(i).unlockcondition);
								te.setUlDesc(dts.get(i).unlockdescription);
								te.setActiveNum(dts.get(i).num);
								
								// 月卡特殊处理
								if (pi.player.getVipMonthType() == 1 && pi.player.getVipMonthDay() > 0 && i == 10)
								{
									type = taskState.substring(i, i + 1);
									if (StringUtil.getInt(type) == 0)
									{
										pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
										taskState = pi.player.getDailyTaskState();
									}
								}
								// vip扫荡券奖励特殊处理
								if (i == 7)
								{
									if (pi.player.getVipLevel() > 0)
									{
										type = taskState.substring(i, i + 1);
										if (StringUtil.getInt(type) == 0)
										{
											pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
											taskState = pi.player.getDailyTaskState();
										}
										List<String> s = new ArrayList<String>();
										VipData vData = VipData.getVipData(pi.player.getVipLevel());
										if (vData != null)
										{
											s.add(1 + "-" + "80001" + "," + vData.mission);
											te.setReward(s);
										}
									}
									else
									{
										continue;
									}
									
								}
								else
								{
									te.setReward(dts.get(i).reward);
								}
								if (completeMap != null && completeMap.size() > 0)
								{
									if (completeMap.containsKey(dts.get(i).id))
									{
										te.setNum(completeMap.get(dts.get(i).id));
									}
									else
									{
										te.setNum(0);
									}
								}
								else
								{
									te.setNum(0);
								}
								te.setSNum(dts.get(i).request);
								
								// 领取体力特殊处理
								// 00:00-13:00发给客户端第一个领取体力值任务 13:00-19：00
								String date1 = "13:00:00";
								String date2 = "00:00:00";
								String date3 = "19:00:00";
								String date4 = "12:00:00";
								String date5 = "18:00:00";
								String today = StringUtil.getDate(System.currentTimeMillis());
								long t1 = StringUtil.getTimeStamp(today + " " + date2);// 00
								long t2 = StringUtil.getTimeStamp(today + " " + date1);// 13
								long t3 = StringUtil.getTimeStamp(today + " " + date3);// 19
								long t4 = StringUtil.getTimeStamp(today + " " + date4);// 12
								long t5 = StringUtil.getTimeStamp(today + " " + date5);// 18
								long time = System.currentTimeMillis();
								if (time - t1 >= 0 && time - t2 <= 0)// 00-13
								{
									if (i == 11)
									{
										if (time - t4 >= 0)// 12-13
										{
											// 更改状态
											type = taskState.substring(i, i + 1);
											if (StringUtil.getInt(type) == 0)
											{
												pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
												taskState = pi.player.getDailyTaskState();
											}
										}
										type = taskState.substring(i, i + 1);
										te.setType(StringUtil.getInt(type));
										tes.add(te);
										b = false;
									}
									
								}
								if (time - t2 > 0 && time - t3 <= 0)// 13-19
								{
									if (i == 12)
									{
										if (time - t5 >= 0)// 18-19
										{
											type = taskState.substring(i, i + 1);
											if (StringUtil.getInt(type) == 0)
											{
												pi.player.setDailyTaskState(StringUtil.replaceStr(taskState, i, 1 + ""));// 修改任务状态
												taskState = pi.player.getDailyTaskState();
											}
										}
										type = taskState.substring(i, i + 1);
										te.setType(StringUtil.getInt(type));
										tes.add(te);
										a = false;
									}
									
								}
								if ((!a && i == 11) || (!b && i == 12))
								{
									type = taskState.substring(i, i + 1);
									if (type != null && StringUtil.getInt(type) < 2)
									{
										te.setType(StringUtil.getInt(type));
										tes.add(te);
									}
								}
								if (a && b)
								{
									if (i != 11 && i != 12)
									{
										type = taskState.substring(i, i + 1);
										if (type != null && StringUtil.getInt(type) < 2)
										{
											te.setType(StringUtil.getInt(type));
											tes.add(te);
										}
									}
								}
							}
						}
						// 排序
						for (int m = 0; m < tes.size(); m++)
						{
							for (int k = tes.size() - 1; k > 0; k--)
							{
								if (tes.get(k).getType() > tes.get(k - 1).getType())// 交换位置
								{
									TaskElement te = new TaskElement();
									te = tes.get(k);
									tes.set(k, tes.get(k - 1));
									tes.set(k - 1, te);
								}
							}
						}
						arrj.tes = tes;
						arrj.active = pi.player.getActive();
						arrj.activeState = pi.player.getActiveState();
						
					}
					else
					{
						arrj.errorCode = errorcode;
					}
					playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pi.player.getId() + "|" + pi.player.getName() + "|等级：" + pi.player.getLevel() + "|领取任务奖励");
				}
				else
				{
					arrj.errorCode = -3;
				}
			}
			else
			{
				arrj.errorCode = -1;
			}
			Cache.recordRequestNum(arrj);
			String msg = JSON.toJSONString(arrj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 领取活跃度奖励 **/
	public ModelAndView activeReward(HttpServletRequest request, HttpServletResponse response)
	{
		
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ActiveJson aj = JSONObject.toJavaObject(jsonObject, ActiveJson.class);
			ActiveResultJson arj = new ActiveResultJson();
			if (aj != null)
			{
				PlayerInfo pi = Cache.getInstance().getPlayerInfo(aj.playerId, request.getSession());
				if (pi != null)
				{
					int errorcode = 0;
					// 校验阶段
					
					int active = aj.getActive();
					
					if (pi.player.getActiveState(active) == -1)
					{
						errorcode = 116;
					}
					else if (pi.player.getActiveState(active) == 0)
					{
						errorcode = 117;
					}
					else if (pi.player.getActiveState(active) == 2)
					{
						errorcode = 118;
					}
					// 功能阶段
					if (errorcode == 0)
					{
						// 领取奖励
						pi.player.rewardActive(active);
						VitalityData vd = VitalityData.getData(active);
						if (null != vd)
						{
							List<String> reward = vd.reward;
							for (String rd : reward)
							{
								if (null != rd && !"".equals(rd) && rd.contains("-"))
								{
									String[] sss = rd.split("-");
									int type = Integer.valueOf(sss[0]);
									if (type > 5)
									{
										int num = Integer.valueOf(sss[1]);
										if (type == 6)
										{
											// 金币
											pi.player.addGold(num);
										}
										else if (type == 7)
										{
											// 人物经验值
											pi.player.addExp(num);
										}
										else if (type == 8)
										{
											// 水晶
											pi.player.addCrystal(num);
										}
										else if (type == 9)
										{
											// 符文值
											pi.player.addRuneNum(num);
										}
										else if (type == 10)
										{
											// 体力
											pi.player.addPower(num, false);
										}
										else if (type == 11)
										{
											// 友情值
											pi.player.addFriendValue(num);
										}
									}
									else
									{
										String[] ssss = sss[1].split(",");
										int itemId = Integer.valueOf(ssss[0]);
										int num = Integer.valueOf(ssss[1]);
										if (type == 1)
										{
											pi.addItem(itemId, num);
										}
										else if (type == 2)
										{
											for (int i = 0; i < num; i++)
											{
												pi.addEquip(itemId);
											}
										}
										else if (type == 3)
										{
											for (int i = 0; i < num; i++)
											{
												pi.addCard(itemId, 1);
											}
										}
										else if (type == 4)
										{
											for (int i = 0; i < num; i++)
											{
												pi.addSkill(itemId, 1);
											}
										}
										else if (type == 5)
										{
											for (int i = 0; i < num; i++)
											{
												pi.addPassiveSkill(itemId);
											}
										}
									}
								}
							}
						}
					}
					arj.errorCode = errorcode;
					playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pi.player.getId() + "|" + pi.player.getName() + "|等级：" + pi.player.getLevel() + "|领取"+active+"活跃度奖励");
				}
				else
				{
					arj.errorCode = -3;
				}
				arj.setActiveState(pi.player.getActiveState());
			}
			else
			{
				arj.errorCode = -1;
			}
			Cache.recordRequestNum(arj);
			String msg = JSON.toJSONString(arj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 兑换激活码 **/
	public ModelAndView getGiftByCode(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			GiftCodeJson gcj = JSONObject.toJavaObject(jsonObject, GiftCodeJson.class);
			GiftCodeResultJson gcrj = new GiftCodeResultJson();
			int errorCode = 0;
			PlayerInfo pi = Cache.getInstance().getPlayerInfo(gcj.getPlayerId(), request.getSession());
			if (pi != null)
			{
				if (gcj.getCode() == null || "".equals(gcj.getCode()))
				{
					errorCode = 92;
				}
				else
				{
					// 访问激活码服务器
					PostMethod post = new PostMethod(Cache.getInstance().gift_code_server);
					post.setParameter("serverId", Cache.getInstance().serverId + "");
					post.setParameter("playerId", pi.player.getId() + "");
					post.setParameter("code", gcj.getCode());
					post.setParameter("password", Constant.GiftPassword);
					HttpClient httpclient = new HttpClient();
					if (httpclient.executeMethod(post) == 200)
					{
						String responseBody = post.getResponseBodyAsString();
						GiftJson gj = JSONObject.toJavaObject(JSON.parseObject(responseBody), GiftJson.class);
						// 0激活码不对 1成功 2玩家已领过,3激活码已使用
						if (gj != null)
						{
							if (gj.result == 0)
							{
								errorCode = 92;
							}
							else if (gj.result == 2)
							{
								errorCode = 94;
							}
							else if (gj.result == 3)
							{
								errorCode = 93;
							}
							else if (gj.result == 1)
							{
								// 领取奖励
								if (gj.gold > 0)
								{
									pi.player.addGold(gj.gold);
								}
								if (gj.crystal > 0)
								{
									pi.player.addCrystal(gj.crystal);
								}
								if (gj.runeNum > 0)
								{
									pi.player.addRuneNum(gj.runeNum);
								}
								if (gj.power > 0)
								{
									pi.player.addPower(gj.power, false);
								}
								if (gj.card != null && gj.card.length() > 0)
								{
									String[] ss = gj.card.split(",");
									for (int k = 0; k < ss.length; k++)
									{
										String[] s = ss[k].split("-");
										int cardId = StringUtil.getInt(s[0]);
										int num = StringUtil.getInt(s[1]);
										for (int i = 0; i < num; i++)
										{
											pi.addCard(cardId, 1);
										}
									}
								}
								if (gj.skill != null && gj.skill.length() > 0)
								{
									String[] ss = gj.skill.split(",");
									for (int k = 0; k < ss.length; k++)
									{
										String[] s = ss[k].split("-");
										int skillId = StringUtil.getInt(s[0]);
										int num = StringUtil.getInt(s[1]);
										for (int i = 0; i < num; i++)
										{
											pi.addSkill(skillId, 1);
										}
									}
								}
								if (gj.pSkill != null && gj.pSkill.length() > 0)
								{
									String[] ss = gj.pSkill.split(",");
									for (int k = 0; k < ss.length; k++)
									{
										String[] s = ss[k].split("-");
										int pSkillId = StringUtil.getInt(s[0]);
										int num = StringUtil.getInt(s[1]);
										for (int i = 0; i < num; i++)
										{
											pi.addPassiveSkill(pSkillId);
										}
									}
								}
								if (gj.equip != null && gj.equip.length() > 0)
								{
									String[] ss = gj.equip.split(",");
									for (int k = 0; k < ss.length; k++)
									{
										String[] s = ss[k].split("-");
										int equipId = StringUtil.getInt(s[0]);
										int num = StringUtil.getInt(s[1]);
										for (int i = 0; i < num; i++)
										{
											pi.addEquip(equipId);
										}
									}
								}
								if (gj.item != null && gj.item.length() > 0)
								{
									String[] ss = gj.item.split(",");
									for (int i = 0; i < ss.length; i++)
									{
										String[] s = ss[i].split("-");
										int itemId = StringUtil.getInt(s[0]);
										int num = StringUtil.getInt(s[1]);
										pi.addItem(itemId, num);
									}
								}
								gcrj.setData(gj);
								playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pi.player.getId() + "|" + pi.player.getName() + "|等级：" + pi.player.getLevel() + "|兑换激活码成功|" + gcj.getCode());
							}
						}
						else
						{
							errorCode = 96;
						}
					}
					else
					{
						errorCode = 96;
					}
					post.releaseConnection();
				}
			}
			else
			{
				errorCode = -3;
			}
			gcrj.errorCode = errorCode;
			// 获取参数
			Cache.recordRequestNum(gcrj);
			String msg = JSON.toJSONString(gcrj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 配置的公告 **/
	public ModelAndView activityGList(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ActivityGJson agj = JSONObject.toJavaObject(jsonObject, ActivityGJson.class);
			ActivityGResultJson agrj = new ActivityGResultJson();
			List<ActivityGElement> ages = new ArrayList<ActivityGElement>();
			if (agj != null)
			{
				PlayerInfo pInfo = Cache.getInstance().getPlayerInfo(agj.playerId, request.getSession());
				if (pInfo != null)
				{
					// 校验阶段
					int errorcode = 0;
					// 校验活动是否存在
					if (errorcode == 0)
					{
						boolean exist = false;
						List<Activity> activities = Cache.getInstance().getActivitys();
						for (Activity ac : activities)
						{
							if (ac.getActivityId() == agj.id)
							{
								exist = true;
								break;
							}
						}
						if (!exist)
						{
							errorcode = 102;
						}
					}
					// 功能阶段
					if (errorcode == 0)
					{
						List<ActivityInfo> ais = Cache.getInstance().getActivityInfos();
						if (ais != null)
						{
							// 排序
							for (int m = 0; m < ais.size(); m++)
							{
								for (int k = ais.size() - 1; k > 0; k--)
								{
									if (ais.get(k).getWeight() > ais.get(k - 1).getWeight())// 交换位置
									{
										ActivityInfo ae = new ActivityInfo();
										ae = ais.get(k);
										ais.set(k, ais.get(k - 1));
										ais.set(k - 1, ae);
									}
								}
							}
							//Collections.sort(ais, new ActivityCompare());
							for (ActivityInfo ai : ais)
							{
								ActivityGElement age = new ActivityGElement();
								if (agj.type == 7)// 公告型
								{
									if (agj.id == ai.getActivityId())
									{
										age.setId(ai.getActivityId());
										age.setAid(ai.getId());
										age.setName(ai.getName());
										age.setHot(ai.getHot());
										age.setType(agj.type);
										ages.add(age);
									}
								}
							}
							agrj.age = ages;
							playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pInfo.player.getId() + "|" + pInfo.player.getName() + "|等级：" + pInfo.player.getLevel() + "|请求公告活动界面!");
						}
						else
						{
							agrj.errorCode = 100;
						}
					}
					else
					{
						agrj.errorCode = errorcode;
					}
				}
				else
				{
					agrj.errorCode = -3;
				}
			}
			else
			{
				agrj.errorCode = -1;
			}
			// 获取参数
			Cache.recordRequestNum(agrj);
			String msg = JSON.toJSONString(agrj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 配置的活动内容 **/
	public ModelAndView activityInfo(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ActivityInfoJson aij = JSONObject.toJavaObject(jsonObject, ActivityInfoJson.class);
			ActivityInfoResultJson airj = new ActivityInfoResultJson();
			List<ActivityInfoExchangeElement> aiees = new ArrayList<ActivityInfoExchangeElement>();
			if (aij != null)
			{
				PlayerInfo pInfo = Cache.getInstance().getPlayerInfo(aij.playerId, request.getSession());
				if (pInfo != null)
				{
					// 校验阶段
					int errorcode = 0;
					if (errorcode == 0)
					{
						if (!UiController.checkMode(19, pInfo))
						{
							errorcode = 56;
						}
					}
					// 校验活动是否存在
					if (errorcode == 0)
					{
						boolean exist = false;
						List<Activity> activities = Cache.getInstance().getActivitys();
						for (Activity ac : activities)
						{
							if (ac.getActivityId() == aij.id)
							{
								exist = true;
								break;
							}
						}
						if (!exist)
						{
							errorcode = 102;
						}
					}
					// 功能阶段
					if (errorcode == 0)
					{
						List<ActivityInfo> ais = Cache.getInstance().getActivityInfos();
						if (ais != null)
						{
							if (aij.type == 7)// 公告型
							{
								for (ActivityInfo ai : ais)
								{
									if (aij.aid == ai.getId())
									{
										airj.setName(ai.getName());
										airj.setContent(ai.getContent());
									}
								}
								playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pInfo.player.getId() + "|" + pInfo.player.getName() + "|等级：" + pInfo.player.getLevel() + "|请求公告活动界面!");
							}
							if (aij.type == 4)// 兑换型
							{
								for (ActivityInfo ai : ais)
								{
									if (aij.id == ai.getActivityId())
									{
										int sell1 = 5;
										int sell2 = 5;
										int sell3 = 5;
										int psole = 0;
										ActivityInfoExchangeElement aiee = new ActivityInfoExchangeElement();
										List<ActivityDElement> ades = new ArrayList<ActivityDElement>();
										airj.setName(ai.getName());
										airj.setContent(ai.getContent());
										aiee.setId(ai.getId());
										aiee.setExchangeType(ai.getExchangeType());
										aiee.setExchangeId(ai.getExchangeId());
										aiee.setExchangeNum(ai.getExchangeNum());
										aiee.setExchangeContext(ai.getExchangeContext());
										aiee.setSole(ai.getSole());
										if (ai.getNeedType() > 0)
										{
											ActivityDElement ae = new ActivityDElement();
											ae.setNeedType(ai.getNeedType());
											ae.setNeedId(ai.getNeedId());
											ae.setNeedNum(ai.getNeedNum());
											int curNeedNum = 0;
											boolean r = false;
											switch (ai.getNeedType())
											{
												case 1:
												case 2:
												case 3:
												case 4:
												case 5:
													r = pInfo.checkExchangeNeedNum(ai.getNeedType(), ai.getNeedId(), ai.getNeedNum());
													break;
												case 6:
													// 金币
													curNeedNum = pInfo.player.getGold();
													break;
												case 8:
													// 钻石
													curNeedNum = pInfo.player.getTotalCrystal();
													break;
												case 9:
													// 符文
													curNeedNum = pInfo.player.getRuneNum();
													break;
												case 10:
													// 体力
													curNeedNum = pInfo.player.getPower();
													break;
											}
											String exnum = pInfo.player.getExchange();// 27-1,
											if (exnum != null && exnum.trim().length() > 0)
											{
												String[] exchange = exnum.split(",");// 27-1
												for (int i = 0; i < exchange.length; i++)
												{// 2
													String[] ex = exchange[i].split("-");// 27
													// 1
													int activityId = Integer.parseInt(ex[0]);
													int num = Integer.parseInt(ex[1]);
													if (activityId == ai.getId())
													{
														psole = num;
													}
													if (activityId == ai.getId() && ai.getSole() > 0 && num >= ai.getSole())
													{
														sell1 = 0;
													}
												}
											}
											if (curNeedNum >= ai.getNeedNum() || r)
											{
												if (sell1 != 0)
												{
													sell1 = 1;
												}
											}
											else
											{
												sell1 = 3;
											}
											aiee.setSell(sell1);
											ae.setCurNeedNum(curNeedNum);
											ades.add(ae);
										}
										if (ai.getNeedType2() > 0)
										{
											ActivityDElement ae2 = new ActivityDElement();
											ae2.setNeedType(ai.getNeedType2());
											ae2.setNeedId(ai.getNeedId2());
											ae2.setNeedNum(ai.getNeedNum2());
											int curNeedNum2 = 0;
											boolean r2 = false;
											switch (ai.getNeedType2())
											{
												case 1:
												case 2:
												case 3:
												case 4:
												case 5:
													r2 = pInfo.checkExchangeNeedNum(ai.getNeedType2(), ai.getNeedId2(), ai.getNeedNum2());
													break;
												case 6:
													// 金币
													curNeedNum2 = pInfo.player.getGold();
													break;
												case 8:
													// 钻石
													curNeedNum2 = pInfo.player.getTotalCrystal();
													break;
												case 9:
													// 符文
													curNeedNum2 = pInfo.player.getRuneNum();
													break;
												case 10:
													// 体力
													curNeedNum2 = pInfo.player.getPower();
													break;
											}
											String exnum = pInfo.player.getExchange();// 27-1,
											if (exnum != null && exnum.trim().length() > 0)
											{
												String[] exchange = exnum.split(",");// 27-1
												for (int i = 0; i < exchange.length; i++)
												{// 2
													String[] ex = exchange[i].split("-");// 27
													// 1
													int activityId = Integer.parseInt(ex[0]);
													int num = Integer.parseInt(ex[1]);
													if (psole == 0)
													{
														if (activityId == ai.getId())
														{
															psole = num;
														}
													}
													if (activityId == ai.getId() && ai.getSole() > 0 && num >= ai.getSole())
													{
														sell2 = 0;
													}
												}
											}
											if (curNeedNum2 >= ai.getNeedNum2() || r2)
											{
												if (sell2 != 0)
												{
													sell2 = 1;
												}
											}
											else
											{
												sell2 = 3;
											}
											if (sell1 == 5)
											{
												aiee.setSell(sell2);
											}
											if (sell1 != 5)
											{
												if (sell2 == 3 || sell1 == 3)
												{
													aiee.setSell(3);
												}
												if (sell3 == 1 && sell1 == 1)
												{
													aiee.setSell(1);
												}
												if ((sell1 == 0 && sell2 != 3) || (sell2 == 0 && sell1 != 3))
												{
													aiee.setSell(0);
												}
											}
											ae2.setCurNeedNum(curNeedNum2);
											ades.add(ae2);
										}
										if (ai.getNeedType3() > 0)
										{
											ActivityDElement ae3 = new ActivityDElement();
											ae3.setNeedType(ai.getNeedType3());
											ae3.setNeedId(ai.getNeedId3());
											ae3.setNeedNum(ai.getNeedNum3());
											int curNeedNum3 = 0;
											boolean r3 = false;
											switch (ai.getNeedType3())
											{
												case 1:
												case 2:
												case 3:
												case 4:
												case 5:
													r3 = pInfo.checkExchangeNeedNum(ai.getNeedType3(), ai.getNeedId3(), ai.getNeedNum3());
													break;
												case 6:
													// 金币
													curNeedNum3 = pInfo.player.getGold();
													break;
												case 8:
													// 钻石
													curNeedNum3 = pInfo.player.getTotalCrystal();
													break;
												case 9:
													// 符文
													curNeedNum3 = pInfo.player.getRuneNum();
													break;
												case 10:
													// 体力
													curNeedNum3 = pInfo.player.getPower();
													break;
											}
											String exnum = pInfo.player.getExchange();// 27-1,
											if (exnum != null && exnum.trim().length() > 0)
											{
												String[] exchange = exnum.split(",");// 27-1
												for (int i = 0; i < exchange.length; i++)
												{// 2
													String[] ex = exchange[i].split("-");// 27
													// 1
													int activityId = Integer.parseInt(ex[0]);
													int num = Integer.parseInt(ex[1]);
													if (psole == 0)
													{
														if (activityId == ai.getId())
														{
															psole = num;
														}
													}
													if (activityId == ai.getId() && ai.getSole() > 0 && num >= ai.getSole())
													{
														sell3 = 0;
													}
												}
											}
											if (curNeedNum3 >= ai.getNeedNum3() || r3)
											{
												if (sell3 != 0)
												{
													sell3 = 1;
												}
											}
											else
											{
												sell3 = 3;
											}
											if (sell1 == 5 && sell2 == 5)
											{
												aiee.setSell(sell3);
											}
											if (sell1 == 5 && sell2 != 5)
											{
												if (sell2 == 3 || sell3 == 3)
												{
													aiee.setSell(3);
												}
												if ((sell2 == 0 && sell3 != 3) || (sell3 == 0 && sell2 != 3))
												{
													aiee.setSell(0);
												}
												if (sell2 == 1 && sell3 == 1)
												{
													aiee.setSell(1);
												}
											}
											if (sell1 != 5 && sell2 == 5)
											{
												if (sell1 == 3 || sell3 == 3)
												{
													aiee.setSell(3);
												}
												if ((sell1 == 0 && sell3 != 3) || (sell3 == 0 && sell1 != 3))
												{
													aiee.setSell(0);
												}
												if (sell1 == 1 && sell3 == 1)
												{
													aiee.setSell(1);
												}
											}
											if (sell1 != 5 && sell2 != 5)
											{
												if (sell1 == 3 || sell2 == 3 || sell3 == 3)
												{
													aiee.setSell(3);
												}
												if ((sell1 == 0 && sell2 != 3 && sell3 != 3) || (sell2 == 0 && sell1 != 3 && sell3 != 3) || (sell3 == 0 && sell1 != 3 && sell2 != 3))
												{
													aiee.setSell(0);
												}
												if (sell1 == 1 && sell2 == 1 && sell3 == 1)
												{
													aiee.setSell(1);
												}
											}
											ae3.setCurNeedNum(curNeedNum3);
											ades.add(ae3);
										}
										aiee.setPSole(psole);
										aiee.ade = ades;
										aiees.add(aiee);
									}
								}
								airj.setExActs(aiees);
								playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pInfo.player.getId() + "|" + pInfo.player.getName() + "|等级：" + pInfo.player.getLevel() + "|请求兑换活动界面!");
							}
						}
						else
						{
							airj.errorCode = 100;
						}
					}
					else
					{
						airj.errorCode = errorcode;
					}
				}
				else
				{
					airj.errorCode = -3;
				}
			}
			else
			{
				airj.errorCode = -1;
			}
			// 获取参数
			Cache.recordRequestNum(airj);
			String msg = JSON.toJSONString(airj);
			// 返回结果
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/** 兑换 **/
	public ModelAndView doExchange(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			// 校验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null)
			{
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			ExchangeJson ej = JSONObject.toJavaObject(jsonObject, ExchangeJson.class);
			ExchangeResultJson erj = new ExchangeResultJson();
			if (ej != null)
			{
				PlayerInfo pInfo = Cache.getInstance().getPlayerInfo(ej.playerId, request.getSession());
				if (pInfo != null)
				{
					// 校验阶段
					int errorcode = 0;
					if (errorcode == 0)
					{
						if (!UiController.checkMode(19, pInfo))
						{
							errorcode = 56;
						}
					}
					List<ActivityInfo> ais = Cache.getInstance().getActivityInfos();
					// 校验是否存在这个活动
					ActivityInfo ai = null;
					if (errorcode == 0)
					{
						for (ActivityInfo temp : ais)
						{
							if (ej.id == temp.getId())
							{
								ai = temp;
							}
						}
						if (ai == null)
						{
							errorcode = 102;
						}
					}
					// 是否还有兑换次数
					if (errorcode == 0)
					{
						String exnum = pInfo.player.getExchange();// 27-1,
						if (exnum != null && exnum.trim().length() > 0)
						{
							String[] exchange = exnum.split(",");// 27-1
							for (int i = 0; i < exchange.length; i++)
							{
								String[] ex = exchange[i].split("-");// 27
								int activityId = Integer.parseInt(ex[0]);
								int num = Integer.parseInt(ex[1]);
								if (activityId == ej.id && ai.getSole() > 0 && num >= ai.getSole())// 30
								{
									errorcode = 101;
									break;
								}
							}
						}
					}
					// 数量是否足够
					if (errorcode == 0)
					{
						// 需要物品1
						if (ai.getNeedType() > 0)
						{
							boolean ischeck = Statics.check(pInfo, ai.getNeedType(), ai.getNeedId(), ai.getNeedNum());
							if (!ischeck)
							{
								errorcode = 103;
							}
						}
						// 需要物品2
						if (ai.getNeedType2() > 0)
						{
							boolean ischeck = Statics.check(pInfo, ai.getNeedType2(), ai.getNeedId2(), ai.getNeedNum2());
							if (!ischeck)
							{
								errorcode = 103;
							}
						}
						// 需要物品3
						if (ai.getNeedType3() > 0)
						{
							boolean ischeck = Statics.check(pInfo, ai.getNeedType3(), ai.getNeedId3(), ai.getNeedNum3());
							if (!ischeck)
							{
								errorcode = 103;
							}
						}
					}
					// 校验背包
					if (errorcode == 0)
					{
						switch (ai.getExchangeType())
						{
							case 1:
								if (pInfo.getItems().size() + ai.getExchangeNum() >= Statics.getPackageNum(pInfo))
								{
									errorcode = 53;
								}
								break;
							case 2:
								if (pInfo.getEquips().size() + ai.getExchangeNum() >= Statics.getPackageNum(pInfo))
								{
									errorcode = 53;
								}
								break;
							case 3:
								if (pInfo.getCards().size() + ai.getExchangeNum() >= Statics.getPackageNum(pInfo))
								{
									errorcode = 53;
								}
								break;
							case 4:
								if (pInfo.getSkills().size() + ai.getExchangeNum() >= Statics.getPackageNum(pInfo))
								{
									errorcode = 53;
								}
								break;
							case 5:
								if (pInfo.getPassiveSkillls().size() + ai.getExchangeNum() >= Statics.getPackageNum(pInfo))
								{
									errorcode = 53;
								}
								break;
						}
					}
					// 功能阶段
					if (errorcode == 0)
					{
						// 兑换后玩家所得
						switch (ai.getExchangeType())
						{
							case 1:
								// 材料
								pInfo.addItem(ai.getExchangeId(), ai.getExchangeNum());
								break;
							case 2:
								// 装备
								for (int i = 0; i < ai.getExchangeNum(); i++)
								{
									pInfo.addEquip(ai.getExchangeId());
								}
								break;
							case 3:// 卡牌
								for (int i = 0; i < ai.getExchangeNum(); i++)
								{
									pInfo.addCard(ai.getExchangeId(), 1);
								}
								break;
							case 4:
								// 主动技能
								for (int i = 0; i < ai.getExchangeNum(); i++)
								{
									pInfo.addSkill(ai.getExchangeId(), 1);
								}
								break;
							case 5:
								// 被动技能
								for (int i = 0; i < ai.getExchangeNum(); i++)
								{
									pInfo.addPassiveSkill(ai.getExchangeId());
								}
								break;
							case 6:
								// 金币
								pInfo.player.addGold(ai.getExchangeNum());
								break;
							case 8:
								// 钻石
								pInfo.player.addCrystal(ai.getExchangeNum());
								break;
							case 9:
								// 符文
								pInfo.player.addRuneNum(ai.getExchangeNum());
								break;
							case 10:
								// 体力
								pInfo.player.addPower(ai.getExchangeNum(), false);
								break;
						}
						// 兑换后玩家所失1
						if (ai.getNeedType() > 0)
						{
							doPlayerRemove(pInfo, ai.getNeedType(), ai.getNeedId(), ai.getNeedNum(), ai.getExchangeContext());
						}
						// 兑换后玩家所失2
						if (ai.getNeedType2() > 0)
						{
							doPlayerRemove(pInfo, ai.getNeedType2(), ai.getNeedId2(), ai.getNeedNum2(), ai.getExchangeContext());
						}
						// 兑换后玩家所失3
						if (ai.getNeedType3() > 0)
						{
							doPlayerRemove(pInfo, ai.getNeedType3(), ai.getNeedId3(), ai.getNeedNum3(), ai.getExchangeContext());
						}
						// 记下这次兑换
						StringBuilder sBuilder = new StringBuilder();
						String exnum = pInfo.player.getExchange();// 27-1,
						if (exnum != null && exnum.trim().length() > 0)
						{
							boolean haveMark = false;// 如果没有这次兑换信息
							String[] exchange = exnum.split(",");// 27-1
							for (int i = 0; i < exchange.length; i++)
							{
								String[] ex = exchange[i].split("-");// 27
								int activityId = Integer.parseInt(ex[0]);
								int num = Integer.parseInt(ex[1]);
								if (activityId == ej.id)// 30
								{
									haveMark = true;
									num = num + 1;
								}
								sBuilder.append(ex[0] + "-" + num + ",");
							}
							if (!haveMark)
							{
								sBuilder.append(ej.id + "-" + 1 + ",");
							}
						}
						else
						{
							sBuilder.append(ej.id + "-" + 1 + ",");
						}
						pInfo.player.setExchange(sBuilder.toString());
					}
					else
					{
						erj.errorCode = errorcode;
					}
				}
				else
				{
					erj.errorCode = -3;
				}
				playlogger.info("|区服：" + Cache.getInstance().serverId + "|玩家：" + pInfo.player.getId() + "|" + pInfo.player.getName() + "|等级：" + pInfo.player.getLevel() + "|参与了兑换活动" + "|兑换ID" + ej.id);
			}
			else
			{
				erj.errorCode = -1;
			}
			// 获取参数
			Cache.recordRequestNum(erj);
			String msg = JSON.toJSONString(erj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
		}
		catch (Exception e)
		{
			// 捕获异常,删掉旧密钥,生成新密钥发给客户端
			errorlogger.error(this.getClass().getName() + "->" + Thread.currentThread().getStackTrace()[1].getMethodName() + "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	// 玩家兑换后所失
	public void doPlayerRemove(PlayerInfo pInfo, int type, int id, int num, String aiDes)
	{
		switch (type)
		{
			case 1:// 材料
			case 2:// 装备
			case 3:
			case 4:
			case 5:
				pInfo.exchange(type, id, num);
				break;
			case 6:
				// 金币
				pInfo.player.removeGold(num);
				break;
			case 8:
				// 钻石
				int[] crystals = pInfo.player.removeCrystal(num);
				MailThread.getInstance().addLogbuy(LogBuy.createLogBuy(pInfo.player.getId(), "兑换|" + aiDes, crystals));
				break;
			case 9:
				// 符文
				pInfo.player.removeRuneNum(num);
				break;
			case 10:
				// 体力
				pInfo.player.removePower(num);
				break;
		}
	}
	
	class ActivityCompare implements Comparator<ActivityInfo>{

		@Override
		public int compare(ActivityInfo o1, ActivityInfo o2)
		{
			return o2.getWeight()-o1.getWeight();
		}

		
	}
}
